<template>
  <div class="user-container">
    <a-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <a-form
          :model="searchForm"
          layout="inline"
          @submit="handleSearch"
        >
          <a-form-item label="用户名">
            <a-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="真实姓名">
            <a-input
              v-model="searchForm.realName"
              placeholder="请输入真实姓名"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              allow-clear
            >
              <a-option :value="1">正常</a-option>
              <a-option :value="0">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮 -->
      <div class="table-actions">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增用户
        </a-button>
        <a-button
          type="outline"
          status="danger"
          :disabled="!selectedKeys.length"
          @click="handleBatchDelete"
        >
          <template #icon>
            <icon-delete />
          </template>
          批量删除
        </a-button>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #avatar="{ record }">
          <a-avatar :src="record.avatar" :size="32">
            {{ record.realName?.charAt(0) }}
          </a-avatar>
        </template>

        <template #status="{ record }">
          <a-tag :color="record.status === 1 ? 'green' : 'red'">
            {{ record.status === 1 ? '正常' : '禁用' }}
          </a-tag>
        </template>

        <template #gender="{ record }">
          <span v-if="record.gender === 1">男</span>
          <span v-else-if="record.gender === 2">女</span>
          <span v-else>未知</span>
        </template>

        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个用户吗？"
              @ok="handleDelete(record)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 用户表单弹窗 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户名" field="username">
              <a-input v-model="formData.username" placeholder="请输入用户名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="真实姓名" field="realName">
              <a-input v-model="formData.realName" placeholder="请输入真实姓名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="邮箱" field="email">
              <a-input v-model="formData.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手机号" field="phone">
              <a-input v-model="formData.phone" placeholder="请输入手机号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="性别" field="gender">
              <a-select v-model="formData.gender" placeholder="请选择性别">
                <a-option :value="1">男</a-option>
                <a-option :value="2">女</a-option>
                <a-option :value="0">未知</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" field="status">
              <a-select v-model="formData.status" placeholder="请选择状态">
                <a-option :value="1">正常</a-option>
                <a-option :value="0">禁用</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item v-if="!formData.id" label="密码" field="password">
          <a-input-password v-model="formData.password" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入备注"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'

// 搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  status: undefined
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedKeys = ref<string[]>([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
  showTotal: true
})

// 表格配置
const columns: TableColumnData[] = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '头像', slotName: 'avatar', width: 80, align: 'center' },
  { title: '用户名', dataIndex: 'username', width: 120 },
  { title: '真实姓名', dataIndex: 'realName', width: 120 },
  { title: '邮箱', dataIndex: 'email', width: 180 },
  { title: '手机号', dataIndex: 'phone', width: 120 },
  { title: '性别', slotName: 'gender', width: 80, align: 'center' },
  { title: '状态', slotName: 'status', width: 80, align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', width: 180 },
  { title: '操作', slotName: 'actions', width: 120, align: 'center', fixed: 'right' }
]

// 行选择配置
const rowSelection = reactive({
  type: 'checkbox' as const,
  showCheckedAll: true,
  onSelect: (rowKeys: string[]) => {
    selectedKeys.value = rowKeys
  },
  onSelectAll: (checked: boolean) => {
    if (checked) {
      selectedKeys.value = tableData.value.map((item: any) => item.id)
    } else {
      selectedKeys.value = []
    }
  }
})

// 表单相关
const formVisible = ref(false)
const formTitle = ref('')
const formRef = ref()
const formData = reactive({
  id: undefined,
  username: '',
  realName: '',
  email: '',
  phone: '',
  gender: 0,
  status: 1,
  password: '',
  remark: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 2, message: '用户名至少2个字符' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码至少6个字符' }
  ]
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    realName: '',
    status: undefined
  })
  handleSearch()
}

// 分页
const handlePageChange = (page: number) => {
  pagination.current = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  formTitle.value = '新增用户'
  resetForm()
  formVisible.value = true
}

// 编辑
const handleEdit = (record: any) => {
  formTitle.value = '编辑用户'
  Object.assign(formData, record)
  formVisible.value = true
}

// 删除
const handleDelete = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 "${record.realName}" 吗？`,
    onOk: async () => {
      try {
        // 调用删除API
        Message.success('删除成功')
        fetchData()
      } catch (error) {
        Message.error('删除失败')
      }
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedKeys.value.length} 个用户吗？`,
    onOk: async () => {
      try {
        // 调用批量删除API
        Message.success('删除成功')
        selectedKeys.value = []
        fetchData()
      } catch (error) {
        Message.error('删除失败')
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  const errors = await formRef.value?.validate()
  if (errors) return

  try {
    if (formData.id) {
      // 更新用户
      Message.success('更新成功')
    } else {
      // 新增用户
      Message.success('新增成功')
    }
    formVisible.value = false
    fetchData()
  } catch (error) {
    Message.error('操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  formVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    username: '',
    realName: '',
    email: '',
    phone: '',
    gender: 0,
    status: 1,
    password: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        username: 'admin',
        realName: '超级管理员',
        email: 'admin@mmc.com',
        phone: '13800138000',
        gender: 1,
        status: 1,
        avatar: '/avatar.png',
        createTime: '2024-01-01 00:00:00'
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    Message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
}

.search-form {
  background: #f7f8fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.table-actions {
  margin-bottom: 16px;
  
  .arco-btn + .arco-btn {
    margin-left: 8px;
  }
}
</style> 